<script setup>
import { ref } from 'vue'
import { addCateServer, editCateServer } from '@/api/article.js'
const dialogVisible = ref(false)
const form = ref(null)
const title = ref('')
const formModel = ref({
  id: '',
  cate_name: '',
  cate_alias: ''
})
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名称必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的大小写字母和数字',
      trigger: 'blur'
    }
  ]
}
const open = obj => {
  dialogVisible.value = true
  // obj 不能与formModel直接绑定,不然改变formModel会影响到表格的展示
  formModel.value = { ...obj }
  if (!formModel.value.id) {
    title.value = '添加分类'
  } else {
    title.value = '编辑分类'
  }
}
// 将open方法暴露出去
defineExpose({ open })
// 调用父组件的方法更新表格
const emit = defineEmits(['success'])
// 添加或修改
const goChange = async () => {
  await form.value.validate()
  if (title.value === '添加分类') {
    await addCateServer(formModel.value)
    ElMessage.success('添加成功')
  } else {
    await editCateServer(formModel.value)
    ElMessage.success('修改成功')
  }
  emit('success')
  dialogVisible.value = false
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    @close="form.resetFields()"
    :title="title"
    width="30%"
  >
    <el-form :model="formModel" ref="form" :rules="rules">
      <el-input
        v-model="formModel.id"
        autocomplete="off"
        style="display: none"
      />
      <el-form-item label="分类名称" label-width="100px" prop="cate_name">
        <el-input v-model="formModel.cate_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="分类别名" label-width="100px" prop="cate_alias">
        <el-input v-model="formModel.cate_alias" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="goChange"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped></style>
